package com.jlz.beans.core;

import java.util.Map;

import com.jlz.beans.def.ColumnBean;
import com.jlz.managers.def.Columns;
import com.julewa.db.mongo.MongoDB;
import com.julewa.db.mongo.Mongoes;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;

public class CategoryTable {
	private MongoDB mongoDB = null;
	private Mongoes mongoes = null;
	private String catecode = null;
	private CategoryBean category = null;
	private ColumnBean root = null;
	//
	public CategoryTable(MongoDB mongoDB, CategoryBean cate, Columns columns, long rootColumnID){
		this.mongoDB = mongoDB;
		this.category = cate;
		this.root = columns.get(rootColumnID);
	}
	
	public ColumnBean getRoot(){
		return root;
	}
	
	public String getPrefix(){
		return this.root.getCode() + ".";
	}
	//
	public Mongoes getMongoes(){
		if(catecode != category.getCode()){
			catecode = category.getCode();
		}else if(mongoes != null){
			return mongoes;
		}
		if(catecode == null)return null;
		mongoes = mongoDB.getMongoes(catecode + "." + root.getCode());
		return mongoes;
	}
	
	public boolean check(DBObject data){
		//TODO 
		return false;
	}
	
	//从一组数据建立一个对象,同时返回数据状态的检查,这是个关键方法
	public CategoryData build(String prefix, Map<String, String[]> map){
		return new CategoryData(prefix, this.root, map);
	}
	
	public CategoryData build(Map<String, String[]> map){
		return new CategoryData(this.getPrefix(), this.root, map);
	}
	
	//
	public DBCursor find(String key, Object ... args){
		return getMongoes().find(key, args);
	}
	
	//
	public boolean insert(DBObject object){
		if(!check(object)){
			return false;
		}
		return getMongoes().insert(object);
	}

	public boolean update(DBObject object){
		if(!check(object)){
			return false;
		}
		return getMongoes().update(object);
	}
	
	//
	public boolean save(DBObject object){
		if(!check(object)){
			return false;
		}
		return getMongoes().save(object);
	}
	
	//
	public boolean remove(DBObject object){
		return getMongoes().remove(object);
	}
}
